import React, {Component} from 'react'
import {connect} from 'react-redux'
import UrlPattern from 'url-pattern'
import {message, Icon, Card} from 'antd'

import HomeworkAnswer from './assignment/homework-answer'
import * as actions from '../actions/homework-answer'

import {studentAnswerPageUrl} from '../constant/constant-url'
import { FormattedMessage } from 'react-intl'
import { convertContent } from '../constant/lang-util'

class StudentAnswerPage extends Component {
  constructor () {
    super()
    this.state = {
      assignmentId: 0,
      quizId: 0
    }
  }

  componentDidMount () {
    const pattern = new UrlPattern(studentAnswerPageUrl)
    const urlParams = pattern.match(this.props.location.pathname)
    this.setState({
      paperId: urlParams.paperId,
      assignmentId: urlParams.assignmentId,
      quizId: urlParams.quizId
    })
    this.props.studentGetHomeworkAnswer(urlParams, this.renderErrorMessage)
  }

  renderErrorMessage () {
    return message.error(convertContent('完成作业才能看呦'))
  }

  getAnswerFile () {
    const { quizCenterUrl } = this.props.settings
    const url = `${quizCenterUrl}/api/v3/homeworkQuizzes/${this.state.quizId}/answerFile`
    window.location.assign(url)
  }

  render () {
    const {homework} = this.props

    return (<div>
      <Card title={<a onClick={() => window.history.back()}><Icon type='arrow-left' /><FormattedMessage id='返回我的作业' /></a>} noHovering bordered={false}>
        <HomeworkAnswer isStudent homeworkQuiz={homework} getAnswerFile={this.getAnswerFile.bind(this)} />
      </Card>
    </div>)
  }
}

const mapStateToProps = (state) => {
  return {
    user: state.user,
    homework: state.homeworkAnswer,
    settings: state.settings
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    studentGetHomeworkAnswer: (data, callback) => dispatch(actions.studentGetHomeworkAnswer(data, callback))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(StudentAnswerPage)
